import { useAnvilCodeStore } from '../store/modules/code';
import { getParamsWithMerge, customApiExecute, modelApiExecute, localApiExecute, findCompByPropInPreview } from '../utils/common-methods';
import { getCacheDict } from '@base/api/base/dict/type';
import { cloneDeep } from 'lodash-es';

export default {
  mounted() {
    this._loadFuncsInSelect();
    this._loadFuncsInAll();
  },
  methods: {
    // 给avue原生下拉框/复选框组/单选框组挂载自定义方法，用于处理字典数据
    _loadFuncsInSelect() {
      const { name } = this.$options;
      if ((name == 'avue-select' || name == 'avue-radio' || name == 'avue-checkbox') && this.$attrs.pageId) {
        console.log('挂载avue字典类组件方法成功');
        this.asyncLoad = () => {
          console.log('加载异步数据');
          this.avueSelectAsyncLoad();
        };
        this.dataFilter = (data) => {
          console.log('过滤数据');
          this.avueSelectDataFilter(data);
        };
      }
    },
    // 给avue原生的组件加上清空数据方法
    _loadFuncsInAll() {
      const { name } = this.$options;
      if (name && name.startsWith('avue-') && this.column && this.$attrs.pageId) {
        console.log('挂载avue组件方法成功');
        this.clear = () => {
          console.log('清空组件值');
          this.avueCompsClear();
        };
      }
    },
    // avue-select的加载异步数据方法
    avueSelectAsyncLoad() {
      const { dicOption, formDataUrl, method, contentType, dicRes, dictionary, remoteType, hookBefore, hookAfter, selectFirst, params, props, noLoading } = this.column;
      if (formDataUrl) {
        try {
          const anvilCodeStore = useAnvilCodeStore();
          const { instance } = anvilCodeStore.getPageForm(this.$attrs.pageId);
          const callback = (response) => {
            let res = response;
            if (hookAfter) {
              console.log('调用后置钩子', hookAfter);
              // 获取当前表单实例
              res = instance[hookAfter](response);
            }
            let dicts = [];
            if (dicRes) {
              dicts = eval(dicRes);
            } else {
              dicts = res;
            }

            console.log('dicts', dicts);
            this.netDic = dicts;

            // 需要找到对应的页面数据的column，然后找到对应组件的dicData并修改
            const columns = [];
            findCompByPropInPreview(columns, this.prop, instance.options);
            console.log('找到对应prop的组件', columns);
            if (columns && columns.length) {
              columns[0].dicData = dicts;
            }

            // 判断新数据列表中是否存在原值，若不存在清空原数据
            if (this.text && dicts.findIndex((item) => item[props.value] === this.text) === -1) {
              this.text = '';
            }
          };

          let Params = getParamsWithMerge(this, params);
          if (hookBefore) {
            console.log('调用前置钩子', hookBefore);
            Params = instance[hookBefore](Params);
          }

          const config = {
            url: formDataUrl,
            method,
            contentType,
            params: Params,
            callback
          };

          switch (remoteType) {
            case 'ajax':
              return customApiExecute(config, { noLoading });
            case 'ajaxModel':
              return modelApiExecute(config, { noLoading });
            case 'ajaxLocal':
              return localApiExecute(config, { noLoading });
          }
        } catch (e) {
          console.error('avueSelectAsyncLoad Error!', e);
        }
      }
    },
    // 根据设定的字典过滤函数对当前字典数据进行过滤,这个函数存在问题，没有保存原有的字典
    avueSelectDataFilter(data) {
      try {
        const { filterFunc } = this.column;
        if (!filterFunc) {
          this.msgError('请先设置过滤函数!');
          return;
        }
        const anvilCodeStore = useAnvilCodeStore();
        const { instance } = anvilCodeStore.getPageForm(this.$attrs.pageId);
        // 需要找到对应的页面数据的column，然后找到对应组件的dicData并修改
        const columns = [];
        findCompByPropInPreview(columns, this.prop, instance.options);
        console.log('找到对应prop的组件', columns, instance);
        let dicts = [];
        if (columns && columns.length) {
          dicts = cloneDeep(columns[0].dicData);
        }
        this.netDic = instance[filterFunc](data, dicts);
      } catch (e) {
        console.error('avueSelectDataFilter Error!', e);
      }
    },
    // 清空组件值
    avueCompsClear() {
      this.text = undefined;
    }
  }
};
